package com.learnyou.server.xingzuo.biz.helper;

import cn.hutool.core.collection.CollectionUtil;
import com.learnyou.server.xingzuo.biz.common.XingzuoConstants;
import com.learnyou.server.xingzuo.dto.wechat.WechatIndustryItem;
import com.learnyou.server.xingzuo.dto.wechat.WechatIndustryResultDTO;
import com.learnyou.server.xingzuo.dto.wechat.WechatTemplateItem;
import com.learnyou.server.xingzuo.dto.wechat.WechatTemplateResultDTO;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class WechatClientBizHelper {
    /**
     * 微信公众号的行业是否合法
     * @param industryResultDTO
     * @return
     */
    public static boolean isIndustryValid(WechatIndustryResultDTO industryResultDTO) {
        boolean isValid = false;
        WechatIndustryItem primary = industryResultDTO.getPrimary_industry();

        isValid = isIndustryItemValid(primary);
        if (!isValid) {
            WechatIndustryItem secondary = industryResultDTO.getSecondary_industry();
            isValid = isIndustryItemValid(secondary);
        }
        return isValid;
    }

    public static boolean isTemplateSettingValid(WechatTemplateResultDTO templateResultDTO) {
        boolean isValid = false;
        if (Objects.nonNull(templateResultDTO) && CollectionUtil.isNotEmpty(templateResultDTO.getTemplate_list())) {
            List<WechatTemplateItem> templateItemList = templateResultDTO.getTemplate_list();
            long count = templateItemList.stream()
                    .filter(item -> isTemplateItemValid(item))
                    // 根据名称去重
                    .map(item-> item.getTitle())
                    .distinct().count();
            isValid = (count == XingzuoConstants.TEMPLATE_NAME_ARRAY.length);
        }
        return isValid;
    }

    private static boolean isTemplateItemValid(WechatTemplateItem templateItem) {
        return templateItem.getPrimary_industry().equals(XingzuoConstants.INDUSTRY_NEED_NAME_FIRST)
                && templateItem.getDeputy_industry().equals(XingzuoConstants.INDUSTRY_NEED_NAME_SECOND)
                && Arrays.stream(XingzuoConstants.TEMPLATE_NAME_ARRAY).filter(item -> item.equals(templateItem.getTitle())).count() == 1;
    }

    private static boolean isIndustryItemValid(WechatIndustryItem industryItem) {
        if (industryItem.getFirst_class().equals(XingzuoConstants.INDUSTRY_NEED_NAME_FIRST) &&
                industryItem.getSecond_class().equals(XingzuoConstants.INDUSTRY_NEED_NAME_SECOND)) {
            return true;
        } else {
            return false;
        }
    }
}
